const { execSQL } = require("../db/mysql");

const getBlogList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `;


    if (author) {
        sql += `and author='${author}' `;
    }

    if (keyword) {
        sql += `and title like '%${keyword}%'`;
    }
    console.log("sql", sql);

    return execSQL(sql)
}
const getBlogDetail = (id) => {
    const sql = `select * from blogs where id='${id}'`

    return execSQL(sql).then(rows => {
        return rows[0]
    })

}

const createNewBlog = (blogData = {}) => {
    const title = blogData.title;
    const content = blogData.content;
    const author = blogData.author;
    const createdAt = Date.now();

    const sql = `
        insert into blogs (title,content,author,createdAt) values('${title}','${content}','${author}',${createdAt})
    `
    return execSQL(sql).then(insertedResult => {
        console.log('insertedResult', insertedResult);
        return {
            id: insertedResult.insertId
        }
    })
}

const updateBlog = (id, blogData = {}) => {
    const title = blogData.title;
    const content = blogData.content;

    const sql = `update blogs set title='${title}', content='${content}' where id=${id}`
    return execSQL(sql).then(updateResult => {
        console.log('updateResult', updateResult);
        if (updateResult.affectedRows > 0) {
            return true;
        }
        return false
    })

}

const deleteBlog = (id, author) => {
    const sql = `delete from blogs where id=${id} and author='${author}'`;
    return execSQL(sql).then(deleteResult => {
        console.log('deleteResult', deleteResult);
        if (deleteResult.affectedRows > 0) {
            return true;
        }
        return false
    })

}

module.exports = {
    getBlogList,
    getBlogDetail,
    createNewBlog,
    updateBlog,
    deleteBlog
}